<script setup lang="ts">
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { watch, inject, ref, onMounted, onBeforeUnmount } from 'vue'
import { FormData } from '@/api/product/list'
import { getListApi } from '@/api/product/classification'
import { Editor } from '@/components/Editor'
import {
  ElRadio,
  ElRadioGroup,
  ElInput,
  ElForm,
  ElFormItem,
  ElDivider,
  ElRow,
  ElMessage,
  ElButton,
  ElIcon,
  ElTable,
  ElTableColumn,
  ElInputNumber,
  ElTreeSelect,
  ElImage
} from 'element-plus'
const emit = defineEmits(['close', 'get-list'])
const currentRow = inject('currentRow') as FormData
const InputRef = ref<InstanceType<typeof ElInput>>()
const formRef = ref<InstanceType<typeof ElForm>>()
const table = ref([] as string[])
const arr: any = ref([])
//合并表格
const objectSpanMethod = ({ rowIndex, columnIndex }: any) => {
  //拿到第一列要合并的行数
  let specList = arr.value.filter((e: any) => e.keys?.length > 0)
  if (columnIndex < specList.length - 1) {
    //列下标小于规格数组长度减一
    let rowSpanNum = 1 //行
    for (let i = columnIndex + 1; i < specList.length; i++) {
      //依次拿到每一列要合并的行数
      rowSpanNum *= specList[i].keys.length
    }
    if (rowIndex % rowSpanNum === 0) {
      //当条件成立时，即合并行数
      return { rowspan: rowSpanNum, colspan: 1 }
    } else {
      return { rowspan: 0, colspan: 0 }
    }
  }
}
let buttonIndex = ref<number | ''>('')
const inputVisible = ref(false)
//显示规格值输入框
const showInput = (index: number, key: string) => {
  // 修改 showInput 函数签名，接收键作为参数
  // 这里你可以根据键的值执行相应的操作
  if (arr.value[index][key] == 3) {
    // 使用键来访问规格项的值
    ElMessage({
      message: '规格值不能超过三个！',
      type: 'warning'
    })
    return false
  }
  inputVisible.value = true
  buttonIndex.value = index
  arr.value[index].bool = true
  arr.value[index].count = arr.value[index].count + 1
}
const handleRadioChange = (value) => {
  currentRow.spec_type = value
}
onMounted(() => {
  if (currentRow.spec) {
    arr.value = currentRow.spec
    arr.value.forEach((item, index) => {
      for (const key of item.keys) {
        // 遍历规格项的键
        console.log(key)
        showInput(index, key) // 将键传递给 showInput 函数
      }
    })
    table.value = currentRow.goods_rule
  }
  getListApidata()
})
const options = ref<Array<{ name: string; id: number }>>([])
const getListApidata = async () => {
  const res = await getListApi({ field: 'id,name,pid' })
  options.value = res.data.list
}
const reset = () => {
  arr.value = []
  table.value = []
  options.value = []
  Object.assign(currentRow, {})
}
watch(
  () => currentRow,
  (row) => {
    if (!row) return
    handleRadioChange(currentRow.spec_type.toString())
  },
  {
    deep: true,
    immediate: true
  }
)
onBeforeUnmount(reset)
</script>

<template>
  <ContentDetailWrap title="商品详情">
    <ElForm ref="formRef" :model="currentRow" label-width="100px">
      <ElDivider borderStyle="none" contentPosition="left">基础信息</ElDivider>
      <div style="display: inline-block">
        <ElFormItem
          prop="name"
          label="商品名称"
          :rules="[
            {
              min: 0,
              max: 50,
              required: true,
              message: '请输入内容,最多支持50字符',
              trigger: 'blur'
            }
          ]"
        >
          <ElInput v-model="currentRow.name" placeholder="请输入内容" disabled />
        </ElFormItem>
      </div>
      <div style="display: inline-block">
        <ElFormItem prop="goods_cate_id_two" label="商品分类" required>
          <ElTreeSelect
            v-model="currentRow.goods_cate_id_two"
            style="width: 240px"
            :data="options"
            disabled
            :render-after-expand="false"
            :props="{ value: 'id', label: 'name' }"
            placeholder="请输入内容"
          />
        </ElFormItem>
      </div>
      <div style="display: inline-block">
        <ElFormItem prop="unit" label="商品单位" required>
          <ElInput v-model="currentRow.unit" placeholder="请输入内容" disabled />
        </ElFormItem>
      </div>
      <!-- <ElFormItem prop="img" label="商品图片" required>
        <AllUpload v-model="currentRow.img" />
      </ElFormItem> -->
      <ElFormItem prop="img" label="商品图片" required>
        <div v-for="fit in currentRow.img" :key="fit">
          <ElImage style="width: 100px; height: 100px; margin-right: 20px" :src="fit" />
        </div>
      </ElFormItem>
      <ElFormItem prop="shelf_life" label="保质期(天)" required>
        <ElInputNumber
          class="setUp"
          controlsPosition="right"
          v-model="currentRow.shelf_life"
          placeholder="保质期(天)"
          :min="0"
          disabled
        />
      </ElFormItem>
      <ElDivider borderStyle="none" contentPosition="left">规格/库存</ElDivider>
      <ElFormItem prop="spec_type" label="规格类型" required>
        <ElRadioGroup v-model="currentRow.spec_type" @change="handleRadioChange">
          <ElRadio label="1" disabled>单规格</ElRadio>
          <ElRadio label="2" disabled>多规格</ElRadio>
        </ElRadioGroup>
      </ElFormItem>
      <div v-if="currentRow.spec_type == 1">
        <div style="display: inline-block">
          <ElFormItem prop="money" label="售价" required>
            <ElInputNumber
              class="setUp"
              controlsPosition="right"
              v-model="currentRow.money"
              placeholder="售价"
              :min="0"
              :precision="2"
              disabled
            />
          </ElFormItem>
        </div>
        <div style="display: inline-block">
          <ElFormItem prop="purchasing_price" label="进价" required>
            <ElInputNumber
              class="setUp"
              controlsPosition="right"
              v-model="currentRow.purchasing_price"
              placeholder="进价"
              :min="0"
              :precision="2"
              disabled
            />
          </ElFormItem>
        </div>
        <div style="display: inline-block">
          <ElFormItem prop="weight" label="商品重量">
            <ElInputNumber
              class="setUp"
              controlsPosition="right"
              v-model="currentRow.weight"
              placeholder="商品重量"
              :min="0"
              disabled
            />
          </ElFormItem>
        </div>
      </div>
      <div v-if="currentRow.spec_type == 2">
        <ElFormItem label="商品规格">
          <div class="box">
            <div class="Specification-header">
              <ElRow class="mb-4">
                <ElButton type="danger" disabled>+添加规格</ElButton>
              </ElRow>
            </div>
            <div v-for="item in arr" :key="item" class="Specification">
              <ElInput v-model="item.name" placeholder="填写规格" style="width: 300px" disabled />
              <ElIcon class="input_icon" :size="15" color="#ccc" disabled>
                <Icon icon="radix-icons:cross-circled" />
              </ElIcon>
              <ElButton style="margin-left: 10px" size="small" disabled> 添加规格值 </ElButton>
              <div class="tag">
                <div class="input" v-for="(_, ind) in item.count" :key="ind">
                  <ElInput
                    v-if="inputVisible && item.bool"
                    placeholder="填写规格值"
                    ref="InputRef"
                    v-model="item.keys[ind]"
                    :value="item.keys[ind]"
                    style="width: 100px"
                    disabled
                  />
                  <ElIcon class="icon-CircleClose" :size="15" color="#ccc" disabled>
                    <Icon icon="radix-icons:cross-circled" />
                  </ElIcon>
                </div>
              </div>
            </div>
          </div>
        </ElFormItem>
        <ElFormItem label="sku列表">
          <div class="box-card">
            <div class="card-header">
              <ElRow class="mb-4">
                <ElButton type="danger" disabled>生成sku</ElButton>
              </ElRow>
            </div>
            <ElTable
              :data="table"
              :span-method="objectSpanMethod"
              style="width: 100%"
              border
              :header-style="{ background: '#f0f0f0' }"
            >
              <ElTableColumn
                v-for="(item, index) in arr.filter((item: any) => item.keys.length)"
                :key="index"
                width="100"
                align="center"
                :prop="'id' + item.name"
                :label="item.name"
              />
              <!-- 预览图 -->
              <!-- <ElTableColumn prop="img" label="预览图" width="220">
                <template #default="{ row }"><Upload v-model="row.img" /></template>
              </ElTableColumn> -->
              <ElTableColumn prop="img" label="预览图" width="220">
                <template #default="{ row }"
                  ><ElImage style="width: 100px; height: 100px" :src="row.img"
                /></template>
              </ElTableColumn>
              <!-- 商品价格 -->
              <ElTableColumn prop="money" label="商品售价" width="220">
                <template #default="{ row }">
                  <ElInputNumber
                    v-model="row.money"
                    controlsPosition="right"
                    size="small"
                    :min="0"
                    :precision="2"
                    disabled
                  />
                </template>
              </ElTableColumn>
              <ElTableColumn prop="money" label="商品进价" width="220">
                <template #default="{ row }">
                  <ElInputNumber
                    v-model="row.purchasing_price"
                    controlsPosition="right"
                    size="small"
                    :min="0"
                    :precision="2"
                    disabled
                  />
                </template>
              </ElTableColumn>
              <!-- 商品重量 -->
              <ElTableColumn prop="weight" label="商品重量" width="220">
                <template #default="{ row }">
                  <ElInputNumber
                    v-model="row.weight"
                    controlsPosition="right"
                    size="small"
                    :min="0"
                    disabled
                  />
                </template>
              </ElTableColumn>
            </ElTable>
          </div>
        </ElFormItem>
      </div>
      <ElFormItem prop="descriptions" label="商品详情" required>
        <Editor v-model="currentRow.descriptions" ref="editorRef" />
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="w-full flex items-center justify-center">
        <BaseButton @click="emit('close')">关闭</BaseButton>
      </div>
    </template>
  </ContentDetailWrap>
</template>
<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.Specification {
  position: relative;
  width: 450px;
}

.input_icon {
  position: absolute;
  right: 0;
  z-index: 999;
}

.box-card {
  /* width: 100%; */
  margin-bottom: 20px;
}

.sku-batch {
  margin-bottom: 12px;
  line-height: 40px;
}

.title {
  margin-right: 15px;
  font-size: 13px;
  line-height: 28px;
}

.setUp {
  width: 220px;
  margin-right: 15px;
}

.setUpButton {
  margin-left: 30px;
}

.input {
  position: relative;
  height: 40px;
  margin: 5px;
}

.Specification-header {
  margin: 10px 0;
}

.icon-CircleClose {
  position: absolute;
  left: 90px;
  z-index: 999;
}

.tag {
  display: flex;
  width: 200px;
  height: 50px;
  justify-content: flex-start;
}
</style>
